import Taro, { Component } from '@tarojs/taro'
import { View, Input, Textarea, Switch } from '@tarojs/components'
import Address from '../../../components/address';
import classnames from 'classnames';
import NavigationBar from '../../../components/navigationBar/index';

import './index.scss'
import { createreceipt, receiptDetail, delreceipt, editreceipt } from '../../../services/address';
import { isPhoneNumber } from '../../../utils/utils';


export default class EditAddress extends Component {

  config = {
    navigationBarTitleText: '',
  }

  state = {
    form: {},
    id: '',
    isSelected: false,
    list: [],
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    applyPersonal: false,
    companyData: {
      'name': '',
      'identify_num': '',
      'mobile': '',
    },
    personalData: {
      'name': '',
      'mobile': '',
    },
  };


  constructor(props) {
    super(props);
    this.state.id = Number(this.$router.params.id || 0);
  }

  componentDidMount() {
    if (this.state.id) {
      Taro.setNavigationBarTitle({
        title: '修改发票簿'
      })
      receiptDetail({
        id: this.state.id
      }).then(res => {
        this.setState({
          form: {
            city: res.city,
            city_name: res.city_name,
            province: res.province,
            province_name: res.province_name,
            region: res.region,
            region_name: res.region_name,
            receiver: res.receiver,
            mobile: res.mobile,
            dft: res.dft,
            address: res.address,
            id: res.id,
          }
        })
      })
    } else {
      Taro.setNavigationBarTitle({
        title: '新建发票簿'
      })
      // setTimeout(() => {
      //   this.setState({
      //     form: {
      //       city:264,
      //       city_name:"晋城市",
      //       province:220,
      //       province_name:"山西省",
      //       region:269,
      //       region_name:"泽州县",
      //       receiver: '123',
      //       mobile: '13412341234',
      //       address: '123',
      //     },
      //     list: [{
      //       id: 220,
      //       region_name: '山西省'
      //     }, {
      //       id: 264,
      //       region_name: '晋城市'
      //     }, {
      //       id: 269,
      //       region_name: '泽州县'
      //     }]
      //   })
      // }, 1000);
    }
  }

  handleText = (key, e) => {
    const { form } = this.state;
    form[key] = e.target.value;
    if (key === 'dft') {
      form[key] = e.target.value ? 1 : 0
    }
    this.setState({
      form,
    })
  }

  save = () => {
    let isReturnFlag = false;
    // if (isPhoneNumber(this.state.companyData.mobile) || isPhoneNumber(this.state.personalData.mobile)) {
    //   Taro.showToast({
    //     title: '手机号码有误',
    //     icon: 'none'
    //   });
    //   return;
    // }
    if (this.state.applyPersonal) {
      console.log(this.state.applyPersonal,this.state.personalData)

      for (let key in this.state.personalData) {
        if (key != 'address') {
          if (!this.state.personalData[key]) {
            isReturnFlag = true;
            Taro.showToast({
              title: '请填写完整',
              icon: 'none'
            });
            break;
          }
        }

      }
      if (isReturnFlag) {
        return;
      }
      if (this.$router.params.id) {
        editreceipt(
          {
            ...this.state.personalData,
            type: 0,
          }
        ).then(res => {
          Taro.showToast({
            title: '修改成功',
            icon: 'none'
          });
          setTimeout(() => {
            Taro.navigateBack()
          }, 2000);
        })
      } else {
        createreceipt({
          ...this.state.personalData,
          type: 0,
        }).then(res => {
          Taro.showToast({
            title: '创建成功',
            icon: 'none'
          });
          setTimeout(() => {
            Taro.navigateBack()
          }, 2000);
        })
      }
    } else {
      for (let key in this.state.companyData) {
        if (key != 'address') {
          if (!this.state.companyData[key]) {
            isReturnFlag = true;
            Taro.showToast({
              title: '请填写完整',
              icon: 'none'
            });
            break;
          }
        }

      }
      if (isReturnFlag) {
        return;
      }
      if (this.$router.params.id) {
        editreceipt( {
          ...this.state.companyData,
          type: 1,
        }).then(res => {
          Taro.showToast({
            title: '修改成功',
            icon: 'none'
          });
          setTimeout(() => {
            Taro.navigateBack()
          }, 2000);
        })
      } else {
        createreceipt( {
          ...this.state.companyData,
          type: 1,
        }).then(res => {
          Taro.showToast({
            title: '创建成功',
            icon: 'none'
          });
          setTimeout(() => {
            Taro.navigateBack()
          }, 2000);
        })
      }
  
    }
  }


  del = () => {
    let that = this;
    Taro.showModal({
      title: '提示',
      content: '你确定删除这个发票簿吗',
      success: function (res) {
        if (res.confirm) {
          delreceipt({
            id: that.$router.params.id
          }).then(res => {
            Taro.redirectTo({
              url: '/subPackageWork/pages/my-address/index'
            })
          })
        }
      }
    })
  }
  handleChange(key, e) {
    let temp = {};
    let data = {};
    temp[key] = e.detail.value;
    if (this.state.applyPersonal) {
      data = Object.assign({}, this.state.personalData, temp);

      this.setState({
        personalData: data
      });
    } else {
      data = Object.assign({}, this.state.companyData, temp);
      this.setState({
        companyData: data
      });
    }
  }
  chooseInvoiceType(isPersonal) {
    this.setState({
      applyPersonal: isPersonal
    });
  }
  render() {
    const { id, applyPersonal, companyData, personalData } = this.state;

    return (
      <View className='edit-address' style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text={id ? '编辑发票簿' : '新建发票簿'} />
        <View className="common-item">
          <View className="text">抬头类型</View>
          <View className="value">
            <View className="company" onClick={this.chooseInvoiceType.bind(this, false)}>
              <View className={!applyPersonal ? 'active circle' : 'circle'}></View>
              <View className="type">企业</View>
            </View>
            <View className="personal" onClick={this.chooseInvoiceType.bind(this, true)}>
              <View className={applyPersonal ? 'active circle' : 'circle'}></View>
              <View className="type">个人</View>
            </View>
          </View>
        </View>
        { !applyPersonal && <View className="company-form">
          <View className="common-item">
            <View className="text">公司抬头</View>
            <View className="value">
              <Input value={companyData['name']} onInput={this.handleChange.bind(this, 'name')} type="text" placeholder="请输入准确的抬头名称" />
            </View>
          </View>
          {/* <View className="common-item">
            <View className="text">公司税号</View>
            <View className="value">
              <Input value={companyData["company_tax"]} onInput={this.handleChange.bind(this, 'company_tax')} type="number" placeholder="请输入税号" />
            </View>
          </View> */}
          <View className="common-item">
            <View className="text">纳税人识别号</View>
            <View className="value">
              <Input value={companyData["identify_num"]} onInput={this.handleChange.bind(this, 'identify_num')} type="text" placeholder="请输入纳税人识别号" />
            </View>
          </View>
          <View className="line"></View>
          <View className="common-item">
            <View className="text">电话号码</View>
            <View className="value">
              <Input value={companyData['mobile']} onInput={this.handleChange.bind(this, 'mobile')} type="number" placeholder="请输入单位电话号码" />
            </View>
          </View>
          <View className="common-item">
            <View className="text">单位地址</View>
            <View className="value">
              <Input value={companyData['address']} onInput={this.handleChange.bind(this, 'address')} type="text" placeholder="请输入单位地址" />
            </View>
          </View>
        </View>}
        {applyPersonal && <View className="personal-form">
          <View className="common-item">
            <View className="text">发票抬头</View>
            <View className="value">
              <Input value={personalData['name']} onInput={this.handleChange.bind(this, 'name')} type="text" placeholder="请输入准确的抬头名称" />
            </View>
          </View>
          <View className="common-item">
            <View className="text">手机号</View>
            <View className="value">
              <Input value={personalData['mobile']} onInput={this.handleChange.bind(this, 'mobile')} type="number" placeholder="请输入手机号" />
            </View>
          </View>
          <View className="common-item">
            <View className="text">地址</View>
            <View className="value">
              <Input value={personalData['address']} onInput={this.handleChange.bind(this, 'address')} type="text" placeholder="请输入地址" />
            </View>
          </View>
        </View>}
        { !applyPersonal &&
          <View className="formitem default">
            <View className="label">
              设置默认发票簿
          </View>
            <Switch checked={companyData.dft} className="switch" color="#000000" onChange={(e) => this.handleText('dft', e)} />
          </View>}
        { applyPersonal &&
          <View className="formitem default">
            <View className="label">
              设置默认发票簿
          </View>
            <Switch checked={personalData.dft} className="switch" color="#000000" onChange={(e) => this.handleText('dft', e)} />
          </View>}
        {
          id ? (
            <View className="btn-box">
              <View className="delete-btn" onClick={this.del}>删除</View>
              <View className="save-btns" onClick={this.save}>保存</View>
            </View>
          ) : <View className="save-btn" onClick={this.save}>保存</View>
        }
        {/* <Address isSelected={isSelected} defaultvalue={list} closeItem={this.closeItem} /> */}
      </View>
    )
  }
}

